#!/bin/sh

. /etc/utils.sh

PATH="/usr/bin/bluetooth:${PATH}"
BLUEZ_STOR_DIR="/user/bluez/lib/bluetooth"
BLUEZ_CONF_DIR="/tmp/bluez/etc/bluetooth"
BLUEZ_MAIN_CONF="${BLUEZ_CONF_DIR}/main.conf"
BLUEZ_INPUT_CONF="${BLUEZ_CONF_DIR}/input.conf"
BT_MAC_FILE="/tmp/btmacaddress"
BSA_DEVICES_FILE="/user/bsa/bt_devices.xml"

# Bluetooth is needed only on TV Box
! is-tv-box && exit 0

# in debug mode, support multiple BT adapters
if [ -f /tmp/DEBUG ]; then
  hci_ifaces=$(cd /sys/kernel/debug/bluetooth; echo hci* 2> /dev/null)
else
  hci_ifaces=hci0
fi

# if there are multiple BT interfaces, use the last one
hci_active=${hci_ifaces##* }

case "$1" in
  start)
    done=/tmp/btlast_$(basename $0).done
    if experiment BluetoothLast && [ ! -f "$done" ]; then
      : > "$done"
      echo "$0: skipping start due to BluetoothLast experiment."
      exit 0
    fi

    BT_MAC=$(cat "${BT_MAC_FILE}")
    BLUEZ_ADAP_DIR="${BLUEZ_STOR_DIR}/${BT_MAC}"
    BLUEZ_DEVC_DIR="${BLUEZ_ADAP_DIR}/cache"

    # On the first BlueZ start, create BlueZ storage directories
    # and import paired remote control devices from BSA to BlueZ
    if [ ! -e "${BLUEZ_ADAP_DIR}" ]; then
      mkdir -p "${BLUEZ_ADAP_DIR}"
      mkdir -p "${BLUEZ_DEVC_DIR}"
      [ -e "${BSA_DEVICES_FILE}" ] && bsa2bluez
    fi

    # Create BlueZ config files
    mkdir -p "${BLUEZ_CONF_DIR}"

    echo "[General]" >"${BLUEZ_MAIN_CONF}"
    echo "Name=GOOGLE-STB" >>"${BLUEZ_MAIN_CONF}"
    echo "Class=0x100" >>"${BLUEZ_MAIN_CONF}"

    echo "[General]" >"${BLUEZ_INPUT_CONF}"
    echo "Encryption=false" >>"${BLUEZ_INPUT_CONF}"
    echo "UserspaceHID=true" >>"${BLUEZ_INPUT_CONF}"

    # link to active hci for gfiber-agent
    rm -f /tmp/hci
    ln -s /sys/kernel/debug/bluetooth/$hci_active /tmp/hci

    # ignore non-active interfaces
    for n in $hci_ifaces; do
      if [ "$n" != "$hci_active" ]; then
        export IGNORE_$n=1
      fi
    done

    # configure BLE connection parameters:
    # - conn_{min,max}_interval = 8  (8 x 1.25ms = 10ms)
    # - conn_latency = 7             (slave can skip 7 connection intervals)
    # - supervision_timeout = 300    (300 x 10ms = 3000ms)
    #   -> connection is declared down if nothing is received in 3000ms
    echo 6 > /tmp/hci/conn_min_interval         # in case current min > new max
    echo 8 > /tmp/hci/conn_max_interval
    echo 8 > /tmp/hci/conn_min_interval
    echo 7 > /tmp/hci/conn_latency
    echo 300 > /tmp/hci/supervision_timeout

    # Start BlueZ stack
    (
      if runnable ti-rcu-audio; then
        echo "$0: starting ti-rcu-audio"
        setuid appclient:video ti-rcu-audio | logos tiaudio &
      fi

      echo "$0: Starting btmon"
      babysit 30 btmon -A -V -t 2>&1 | logos btmon &
      sleep 1

      echo "$0: Starting bluetoothd"
      babysit 30 bluetoothd -n -d -E 2>&1 | logos bluez &
      sleep 3

      echo "$0: Starting gfiber-agent"
      babysit 30 gfiber-agent "${BLUEZ_ADAP_DIR}" 2>&1 | logos bluez-agent &

      echo >/tmp/S31bluez_done
    ) &
    ;;
  stop)
    wait-until-created /tmp/S31bluez_done
    for n in $hci_ifaces; do hciconfig $n down; done
    rm -f /tmp/hci
    pkillwait -x gfiber-agent
    pkillwait -x bluetoothd
    pkillwait -x btmon
    rm -f /tmp/S31bluez_done
    ;;
  restart)
    $0 stop; $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac
